<?php
require __DIR__ . '/inc/app.php';

$isCliRefresh = PHP_SAPI === 'cli' && isset($argv[1]) && $argv[1] === 'refresh';
if ($isCliRefresh) {
	$_SERVER['REQUEST_URI'] = '/';
	$_SERVER['HTTP_HOST'] = 'localhost';
	$_GET = array();
}

$cfg = app_config();
$force = $isCliRefresh || ($cfg['refresh_key'] !== '' && isset($_GET['refresh']) && hash_equals($cfg['refresh_key'], (string) $_GET['refresh']));
$data = schedule_load($force);
$listed = listed_matches($data['matches']);
if ($force && !$isCliRefresh) {
	baidu_submit($listed);
}
if ($isCliRefresh) {
	ob_start();
}
$site = site_profile();
$origin = request_origin();
$route = resolve_route(request_path());
$matches = filter_matches($listed, $route);
$match = null;
if ($route['kind'] === 'match') {
	$match = find_match($listed, $route['id']);
	$expect = '/live/' . $route['sport'] . '/' . $route['id'] . '.html';
	if (!$match || match_path($match) !== $expect) {
		$route = array('kind' => 'miss');
		$match = null;
	}
}

if ($route['kind'] === 'robots') {
	header('Content-Type: text/plain; charset=UTF-8');
	echo "User-agent: *\n";
	echo "Allow: /\n";
	echo "Disallow: /data/\n";
	echo "Disallow: /inc/\n";
	echo "Disallow: /e/\n";
	echo "Disallow: /d/\n";
	echo "Disallow: /search/\n";
	echo "Disallow: /tiao.html\n";
	echo "Disallow: /tiao.js\n";
	echo "Disallow: /*?\n\n";
	echo "User-agent: Baiduspider\n";
	echo "Allow: /\n";
	echo "Disallow: /data/\n";
	echo "Disallow: /inc/\n";
	echo "Disallow: /e/\n";
	echo "Disallow: /d/\n";
	echo "Disallow: /search/\n";
	echo "Disallow: /tiao.html\n";
	echo "Disallow: /tiao.js\n";
	echo "Disallow: /*?\n";
	echo "Clean-param: utm_source&utm_medium&utm_campaign&utm_term&utm_content&from&spm&bd_vid&refresh /\n\n";
	echo "User-agent: Baiduspider-image\nAllow: /\n\n";
	echo "User-agent: Baiduspider-render\nAllow: /\n\n";
	echo 'Sitemap: ' . $origin . "/sitemap.xml\n";
	exit;
}

$entries = public_entries($listed);
if ($route['kind'] === 'sitemap' && $route['fmt'] === 'xml') {
	header('Content-Type: application/xml; charset=UTF-8');
	echo '<?xml version="1.0" encoding="UTF-8"?>' . "\n";
	echo '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">' . "\n";
	foreach ($entries as $entry) {
		echo '  <url><loc>' . e($origin . $entry['loc']) . '</loc><lastmod>' . e($entry['lastmod']) . '</lastmod><changefreq>' . e($entry['freq']) . '</changefreq><priority>' . e($entry['pri']) . '</priority></url>' . "\n";
	}
	echo "</urlset>\n";
	exit;
}

$head = page_head($route, $site, $match);
if ($route['kind'] === 'miss') {
	http_response_code(404);
	header('X-Robots-Tag: noindex');
}
header('Content-Type: text/html; charset=UTF-8');
$graph = page_graph($route, $site, $origin, $head, $matches, $match);
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="applicable-device" content="pc,mobile">
<meta http-equiv="Cache-Control" content="no-transform">
<title><?php echo e($head['title']); ?></title>
<meta name="keywords" content="<?php echo e($head['keywords']); ?>">
<meta name="description" content="<?php echo e($head['description']); ?>">
<meta name="robots" content="<?php echo $route['kind'] === 'miss' ? 'noindex' : 'index,follow'; ?>">
<link rel="canonical" href="<?php echo e($origin . $head['path']); ?>">
<link rel="shortcut icon" href="/favicon.ico" type="image/x-icon">
<link href="/static/css/bootstrap.min.css" rel="stylesheet" type="text/css">
<link href="/static/css/style.css" rel="stylesheet" type="text/css">
<script src="/static/js/jquery-3.2.1.min.js"></script>
<script type="application/ld+json"><?php echo json_ld($graph); ?></script>
</head>
<body>
<?php render_header($site, $route); ?>
<div class="container-xl main">
  <div class="row">
    <div class="col main-left">
      <?php render_crumb($head); ?>
      <?php if ($route['kind'] === 'home' || $route['kind'] === 'sport' || $route['kind'] === 'league') { ?>
      <h1 class="page-hero"><?php echo e($head['h1']); ?></h1>
      <?php } else { ?>
      <h1 class="h4 mb-3"><?php echo e($head['h1']); ?></h1>
      <?php } ?>
      <?php if ($route['kind'] === 'miss') { ?>
      <p>这个页面不存在。可以回到<a href="/">首页</a>查看今日赛程。</p>
      <?php } elseif ($route['kind'] === 'sitemap') { ?>
      <p><?php echo e($head['description']); ?></p>
      <ul>
        <?php foreach ($entries as $entry) { ?>
        <li><a href="<?php echo e($entry['loc']); ?>"><?php echo e($origin . $entry['loc']); ?></a></li>
        <?php } ?>
      </ul>
      <?php } elseif ($route['kind'] === 'match') { ?>
      <?php render_match($match, $site, $listed); ?>
      <?php } else { ?>
      <div class="card card-flat items-box-group">
        <div class="card-header">
          <h2 class="card-title float-left"><?php echo e($head['h1']); ?></h2>
        </div>
        <p class="px-3 mb-2"><?php echo e($head['description']); ?></p>
        <?php if (!empty($data['error'])) { ?><p class="px-3"><?php echo e($data['error']); ?></p><?php } ?>
        <?php if (!empty($data['via'])) { ?><p class="px-3 text-small text-muted">赛程来自数据库 <?php echo e($data['via']); ?></p><?php } ?>
        <?php render_matches($matches); ?>
      </div>
      <?php } ?>
    </div>
    <?php if ($route['kind'] !== 'miss' && $route['kind'] !== 'sitemap') { render_news($data); } ?>
  </div>
</div>
<?php render_footer($site); ?>
<script src="/static/js/bootstrap.bundle.min.js"></script>
<?php if ($route['kind'] !== 'miss') { ?>
<script>
(function () {
  var bp = document.createElement('script');
  bp.src = location.protocol === 'https:' ? 'https://zz.bdstatic.com/linksubmit/push.js' : 'http://push.zhanzhang.baidu.com/push.js';
  var s = document.getElementsByTagName('script')[0];
  if (s && s.parentNode) { s.parentNode.insertBefore(bp, s); }
})();
</script>
<?php } ?>
</body>
</html>
<?php
if (!empty($isCliRefresh)) {
	$html = ob_get_clean();
	$indexFile = __DIR__ . '/index.html';
	file_put_contents($indexFile, $html);
	@chmod($indexFile, 0644);
	$via = isset($data['via']) && $data['via'] !== '' ? ' via=' . $data['via'] : '';
	$sample = '';
	if (!empty($listed[0])) {
		$sample = ' first=' . $listed[0]['time'] . ' ' . $listed[0]['home'] . 'VS' . $listed[0]['away'];
	}
	echo 'matches=' . count($listed) . ' from=' . $data['from'] . $via . $sample . PHP_EOL;
	echo 'wrote=' . $indexFile . PHP_EOL;
	echo 'baidu=' . baidu_submit($listed) . PHP_EOL;
	exit(empty($data['matches']) ? 1 : 0);
}

function page_head($route, $site, $match)
{
	$name = $site['name'];
	if ($route['kind'] === 'sport') {
		$label = $route['sport'] === 'lanqiu' ? '篮球' : '足球';
		return array(
			'title' => $label . '赛程_今日' . $label . '比赛时间_' . $name,
			'keywords' => $label . '赛程,今日' . $label . '比赛,' . $name,
			'description' => $name . '整理今日' . $label . '赛程，列出开球时间、对阵和比赛状态。',
			'path' => '/live/' . $route['sport'],
			'h1' => '今日' . $label . '赛程',
			'crumb' => array(array('/', '首页'), array('', '今日' . $label . '赛程')),
		);
	}
	if ($route['kind'] === 'league') {
		$league = $route['page']['name'];
		$sportPath = $route['page']['sport'] === 'lanqiu' ? '/live/lanqiu' : '/live/zuqiu';
		$sportLabel = $route['page']['sport'] === 'lanqiu' ? '篮球赛程' : '足球赛程';
		return array(
			'title' => $league . '赛程_' . $league . '比赛时间_' . $name,
			'keywords' => $league . '赛程,' . $league . '比赛时间,' . $name,
			'description' => $name . '整理' . $league . '近期赛程，列出开球时间、对阵和比赛状态。',
			'path' => $route['page']['path'],
			'h1' => $league . '赛程',
			'crumb' => array(array('/', '首页'), array($sportPath, $sportLabel), array('', $league)),
		);
	}
	if ($route['kind'] === 'match' && $match) {
		$vs = $match['home'] . 'VS' . $match['away'];
		$sportPath = ((int) $match['type'] === 2) ? '/live/lanqiu' : '/live/zuqiu';
		$sportLabel = ((int) $match['type'] === 2) ? '篮球赛程' : '足球赛程';
		return array(
			'title' => $match['time'] . ' ' . $vs . ' ' . $match['league'] . '赛程-' . $name,
			'keywords' => $vs . ',' . $match['league'] . '赛程,' . $name,
			'description' => $match['time'] . ' ' . $match['league'] . '，' . $match['home'] . '对阵' . $match['away'] . '。' . $name . '列出这场比赛的开球时间和对阵。',
			'path' => match_path($match),
			'h1' => $vs,
			'crumb' => array(
				array('/', '首页'),
				array($sportPath, $sportLabel),
				array(league_path($match['league']), $match['league']),
				array('', $vs),
			),
		);
	}
	if ($route['kind'] === 'sitemap') {
		return array(
			'title' => $name . '网站地图',
			'keywords' => $name . ',网站地图',
			'description' => $name . '的赛程页面列表，包含首页、联赛页和比赛页。',
			'path' => '/sitemap.html',
			'h1' => $name . '网站地图',
			'crumb' => array(array('/', '首页'), array('', '网站地图')),
		);
	}
	if ($route['kind'] === 'miss') {
		return array(
			'title' => '页面不存在-' . $name,
			'keywords' => $name,
			'description' => '这个页面不存在。',
			'path' => request_path(),
			'h1' => '页面不存在',
			'crumb' => array(array('/', '首页'), array('', '页面不存在')),
		);
	}
	return array(
		'title' => $site['title'],
		'keywords' => $site['keywords'],
		'description' => $site['description'],
		'path' => '/',
		'h1' => $name . '今日赛程',
		'crumb' => array(),
	);
}

function page_graph($route, $site, $origin, $head, $matches, $match)
{
	$crumbs = array();
	$position = 1;
	if (!empty($head['crumb'])) {
		foreach ($head['crumb'] as $item) {
			$node = array('@type' => 'ListItem', 'position' => $position, 'name' => $item[1]);
			if ($item[0] !== '') {
				$node['item'] = $origin . $item[0];
			}
			$crumbs[] = $node;
			$position++;
		}
	}
	$graph = array(
		array('@type' => 'WebSite', 'name' => $site['name'], 'url' => $origin . '/'),
	);
	if ($crumbs) {
		$graph[] = array('@type' => 'BreadcrumbList', 'itemListElement' => $crumbs);
	}
	if ($route['kind'] === 'match' && $match) {
		$graph[] = event_node($match, $origin);
	} elseif ($route['kind'] === 'home' || $route['kind'] === 'sport' || $route['kind'] === 'league') {
		$items = array();
		$position = 1;
		foreach (array_slice($matches, 0, 30) as $item) {
			$items[] = array(
				'@type' => 'ListItem',
				'position' => $position,
				'url' => $origin . match_path($item),
				'name' => $item['home'] . ' vs ' . $item['away'],
			);
			$position++;
		}
		if ($items) {
			$graph[] = array(
				'@type' => 'ItemList',
				'url' => $origin . $head['path'],
				'itemListElement' => $items,
			);
		}
	}
	return array('@context' => 'https://schema.org', '@graph' => $graph);
}

function render_header($site, $route)
{
	$sport = '';
	$leaguePath = '';
	if ($route['kind'] === 'sport') {
		$sport = $route['sport'];
	} elseif ($route['kind'] === 'league') {
		$sport = $route['page']['sport'];
		$leaguePath = $route['page']['path'];
	}
	?>
<header class="sticky-top">
  <div class="header-content">
    <nav class="navbar navbar-dark navbar-expand-lg bg-info">
      <div class="container-xl">
        <a class="navbar-brand" href="/" title="<?php echo e($site['name']); ?>"><?php echo e($site['name']); ?></a>
        <span class="head-kicker d-none d-md-inline">今日赛程</span>
        <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="打开菜单">
          <span class="navbar-toggler-icon"></span>
        </button>
        <div class="collapse navbar-collapse" id="navbarSupportedContent">
          <ul class="navbar-nav mr-auto">
            <li class="nav-item"><a class="nav-link" href="/" title="首页">首页</a></li>
            <li class="nav-item"><a class="nav-link" href="/live/zuqiu" title="足球赛程">足球赛程</a></li>
            <li class="nav-item"><a class="nav-link" href="/live/lanqiu" title="篮球赛程">篮球赛程</a></li>
          </ul>
        </div>
      </div>
    </nav>
  </div>
  <div class="container-xl video_nav">
    <div class="layui-tab layui-tab-brief">
      <ul class="layui-tab-title">
        <?php foreach (league_pages() as $page) { ?>
        <li class="layui-nav-item"><a title="<?php echo e($page['name']); ?>赛程" href="<?php echo e($page['path']); ?>"><?php echo e($page['name']); ?></a></li>
        <?php } ?>
      </ul>
    </div>
  </div>
</header>
<div class="container-xl">
  <div class="ranking-nav-group my-2">
    <div<?php echo $route['kind'] === 'home' ? ' class="self"' : ''; ?>><a href="/">全部赛程</a></div>
    <div<?php echo $sport === 'zuqiu' && $leaguePath === '' ? ' class="self"' : ''; ?>><a href="/live/zuqiu">足球赛程</a></div>
    <div<?php echo $sport === 'lanqiu' && $leaguePath === '' ? ' class="self"' : ''; ?>><a href="/live/lanqiu">篮球赛程</a></div>
  </div>
</div>
	<?php
}

function render_crumb($head)
{
	if (empty($head['crumb'])) {
		return;
	}
	echo '<p class="text-small text-muted">';
	$last = count($head['crumb']) - 1;
	foreach ($head['crumb'] as $i => $item) {
		if ($i > 0) {
			echo ' &gt; ';
		}
		if ($item[0] !== '' && $i !== $last) {
			echo '<a href="' . e($item[0]) . '">' . e($item[1]) . '</a>';
		} else {
			echo e($item[1]);
		}
	}
	echo '</p>';
}

function render_matches($matches)
{
	if (!$matches) {
		echo '<div class="card-body">暂时没有赛程。请先执行 php sync.php，日志出现 synced=数字后再刷新。</div>';
		return;
	}
	echo '<div class="items-group">';
	foreach ($matches as $match) {
		$status = match_status($match);
		$path = match_path($match);
		$play = play_href($match, $status, $path);
		$playAttr = $play === $path ? '' : ' target="_blank" rel="nofollow noopener"';
		$when = iso_time($match['timestamp']);
		echo '<div class="card-body pt-0 live">';
		echo '<div class="list-group list-group-flush list-group-flat pic">';
		echo '<div class="list-group-item list-group-item-action d-flex justify-content-between align-items-center live-item">';
		echo '<div class="d-flex align-items-center match-base"><span class="match-league ml-3 pt-3">';
		echo '<a href="' . e(league_path($match['league'])) . '"><b>' . e($match['league']) . '</b></a> ';
		echo '<time class="match-time-s"' . ($when !== '' ? ' datetime="' . e($when) . '"' : '') . '>' . e($match['time']) . '</time>';
		echo '</span></div>';
		echo '<div class="d-flex align-items-center match-info">';
		echo '<div class="d-flex align-items-center justify-content-end team-info">';
		echo '<a class="flex-1 line-1" href="' . e($path) . '" title="' . e($match['home']) . '">' . e($match['home']) . '</a>';
		if ($match['home_img'] !== '') {
			echo '<img alt="' . e($match['home']) . '" src="' . e($match['home_img']) . '" loading="lazy" decoding="async">';
		}
		echo '</div><div class="team-score"><span>VS</span></div>';
		echo '<div class="d-flex align-items-center team-info">';
		if ($match['away_img'] !== '') {
			echo '<img alt="' . e($match['away']) . '" src="' . e($match['away_img']) . '" loading="lazy" decoding="async">';
		}
		echo '<a class="flex-1 line-1" href="' . e($path) . '" title="' . e($match['away']) . '">' . e($match['away']) . '</a>';
		echo '</div></div>';
		echo '<span class="match-play"><a href="' . e($play) . '"' . $playAttr . ' title="' . e($match['home'] . 'VS' . $match['away']) . '">';
		echo '<span class="bs_ztai badge ' . e(status_class($status)) . ' p-2">' . e($status) . '</span>';
		echo '</a></span></div></div></div>';
	}
	echo '</div>';
}

function render_match($match, $site, $listed)
{
	$status = match_status($match);
	echo '<p>' . e($match['time']) . ' ' . e($match['league']) . '，' . e($match['home']) . '对阵' . e($match['away']) . '。当前状态：' . e($status) . '。</p>';
	render_matches(array($match));
	if ($match['url'] !== '' && link_rel($match['url']) === 'nofollow') {
		echo '<p class="text-small">赛程来源：<a href="' . e($match['url']) . '" rel="nofollow">' . e($match['home'] . 'VS' . $match['away']) . '</a></p>';
	}
	$related = array();
	foreach ($listed as $item) {
		if (match_path($item) === match_path($match)) {
			continue;
		}
		if ($item['league'] !== $match['league']) {
			continue;
		}
		$related[] = $item;
		if (count($related) >= 8) {
			break;
		}
	}
	if ($related) {
		echo '<h2 class="h5 mt-4">同联赛赛程</h2>';
		render_matches($related);
	}
}

function render_news($data)
{
	$side = array(
		array('足球新闻', $data['football']),
		array('篮球新闻', $data['basketball']),
	);
	echo '<div class="main-right">';
	foreach ($side as $block) {
		if (!$block[1]) {
			continue;
		}
		echo '<div class="card card-flat"><div class="card-header"><h2 class="card-title float-left">' . e($block[0]) . '</h2></div><div class="card-body">';
		foreach ($block[1] as $news) {
			$rel = link_rel($news['url']);
			echo '<div class="news-top-item"><h3 class="h6 content"><a href="' . e($news['url']) . '" title="' . e($news['title']) . '"' . ($rel !== '' ? ' rel="' . e($rel) . '"' : '') . '><span class="title">' . e($news['title']) . '</span></a></h3></div>';
		}
		echo '</div></div>';
	}
	echo '</div>';
}

function render_footer($site)
{
	?>
<footer class="footer">
  <div class="container-xl">
    <p class="white"><?php echo e($site['name']); ?>提供足球、篮球赛程，方便查看开球时间和对阵。</p>
    <p class="white">
      <a href="/">首页</a>
      <a href="/live/zuqiu">足球赛程</a>
      <a href="/live/lanqiu">篮球赛程</a>
      <a href="/sitemap.html">网站地图</a>
    </p>
    <p class="copyright">Copyright © 2021-<?php echo date('Y'); ?> <?php echo e($site['name']); ?></p>
  </div>
</footer>
	<?php
}
